package com.aglhz.nature.presenter;



import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.widget.Toast;

import com.aglhz.nature.constants.ServerAPI;
import com.aglhz.nature.events.LoginViewEvent;
import com.aglhz.nature.events.MyselfViewEvent;
import com.aglhz.nature.events.ShopListViewEvent;
import com.aglhz.nature.modle.LoginBean;
import com.aglhz.nature.modle.ShopListBean;
import com.aglhz.nature.modle.WXUserInfo;
import com.aglhz.nature.modle.item.LoginData;
import com.aglhz.nature.presenter.base.BasePresenter;
import com.aglhz.nature.utils.AsyncHttpCilentUtil;
import com.aglhz.nature.view.LoginActivity;
import com.aglhz.nature.view.MainActivity;
import com.aglhz.nature.view.iv.LoginView;
import com.aglhz.nature.view.weixin.WeiXinLoginActivity;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.TextHttpResponseHandler;


public class LoginPresenter extends BasePresenter{
	private static String TAG = LoginPresenter.class.getName();
	private String openid;
	private String access_token;
	private String unionid;
	private String nickname;
	private String headimgurl;
	private WXUserInfo wxUserInfo;
	
	// view
		private LoginView  loginView;
	// data
	private LoginBean loginBean;
	private LoginData data;
	public LoginPresenter(LoginView view,Context context) {
		super();
		loginView = view;
		super.setContext(context);
	}
	
	
	// /*********************data operation*******************///
				public void loadLoginData() {
					String user=loginView.getUser();
					String password=loginView.getPassword();
					
					this.loadLoginBean(user,password);
					// save remote data
					
				}


				
				// /*********************view operation*******************///			
				public void show() {
					int returnCode = Integer.parseInt(loginBean.getOther().getCode());
					loginView.showToast(returnCode);		
							}	
				
				public void showLoseToast(){
					loginView.showLostToast();
				}
				
				///********************view operation*******************///
				@Subscribe(threadMode = ThreadMode.MAIN)
				public void onEventLoginViewThread(LoginViewEvent event) {

					String msg = event.getMessage();
					// update UI By event
					if ( LoginViewEvent.EVENT_UPDATE_LOGIN_MESSAGE == msg) {
						// update grid view
						
						this.saveNormalInfo();
						this.saveNormalToken();
						this.saveNormalName();
						this.saveNormalIntegral();
						this.saveNormalNumber();
						this.show();
					} else if( LoginViewEvent.EVENT_UPDATE_UNLOGIN_MESSAGE == msg){
						this.getLoseInfo();
						this.showLoseToast();
					}else if(LoginViewEvent.EVENT_UPDATE_WXLOGIN_MESSAGE == msg){
						loginView.saveWXToken();
						loginView.intoIntent();
					}
					

				}			
				
				public String getLoseInfo(){
					return loginBean.getOther().getMessage();
				}
		public String getToken() {
			return wxUserInfo.getData().getMemberInfo().getToken();
		}

				
	public void saveNormalInfo(){
		Boolean isChecked= loginView.isChecked();
		//保存用户头像等信息
		loginView.saveNormalInfo();
		if(isChecked){
			//保存帐号密码
			loginView.saveEditTextInfo();
			
		}else{
			
		}
				
	}			
				
				
	public String saveNormalToken(){
		String normalToken=loginBean.getData().getMemberInfo().getToken();
		return normalToken;
		
	}			
				
public String saveNormalName(){
	String normalName=loginBean.getData().getMemberInfo().getName();
	return normalName;
	
}

public String saveNormalIntegral(){
	String Integral=loginBean.getData().getMemberInfo().getPoint();
	return Integral;
	
}

public String saveNormalNumber(){
	String NorNumber=loginBean.getData().getMemberInfo().getMoney();
	return NorNumber;
}

	public void loadLoginBean(String user,String password) {
		// http://h5.aglhz.com/gc_community/client/login.do?user=123aa&pwd=1
		String url = ServerAPI.APIHEARD+ServerAPI.LOGIN+"?user="+user+"&pwd="+password;

		AsyncHttpClient client = AsyncHttpCilentUtil.getInstance(super.getContext());
		client.get(url, new TextHttpResponseHandler() {
			
			@Override
			public void onSuccess(int statusCode,
					cz.msebera.android.httpclient.Header[] headers,
					String responseString) {
				 try {
					
					 Gson gson = new Gson();
					
					 LoginBean loBean = gson.fromJson(responseString,
							 LoginBean.class);
					 loginBean= ( LoginBean) loBean.clone();
					
					data = loginBean.getData();
					int code = Integer.parseInt(loginBean.getOther().getCode());
					if(code==200){
						 // send event
						LoginViewEvent event = new  LoginViewEvent(
								LoginViewEvent.EVENT_UPDATE_LOGIN_MESSAGE);
						 EventBus.getDefault().post(event);
					}else{
						LoginViewEvent event = new  LoginViewEvent(
								LoginViewEvent.EVENT_UPDATE_UNLOGIN_MESSAGE);
						
						 EventBus.getDefault().post(event);
					}
					
					 
					 } catch (Exception e) {
					 e.printStackTrace();
					 }
				
				
			}
			
			@Override
			public void onFailure(int statusCode,
					cz.msebera.android.httpclient.Header[] headers,
					String responseString, Throwable throwable) {
				
			}
		

	

	
		});

		
	}
	// 第一次登陆上传和返回用户信息
		public void getUserInfo() {
			openid = loginView.setOpenid();
			access_token = loginView.setAccess_token();
			unionid = loginView.setUnionid();
			nickname = loginView.setNickname();
			headimgurl = loginView.setHeadimgurl();
			String url = ServerAPI.APIHEARD+ServerAPI.WXLOGIN+"?newAuth=true&token="
					+ access_token
					+ "&userId="
					+ openid
					+ "&userName="
					+ nickname
					+ "&headURL="
					+ headimgurl
					+ "&type=wxsession&unionid="
					+ unionid;
			 AsyncHttpClient client =  AsyncHttpCilentUtil.getInstance(super.getContext());
			
			
			client.post(url, new TextHttpResponseHandler() {

				@Override
				public void onSuccess(int statusCode,
						cz.msebera.android.httpclient.Header[] headers,
						String responseString) {
					try {

						Gson gson = new Gson();

						WXUserInfo UserInfo = gson.fromJson(responseString,
								WXUserInfo.class);
						
						wxUserInfo = (WXUserInfo) UserInfo.clone();
						int infocode = Integer.parseInt(wxUserInfo.getOther()
								.getCode());
						if (infocode == 200) {
							/*Log.e("-------private void getUserInfo() {;_________________",
									"--------url---------------"
											+ wxUserInfo.getData().getMemberInfo()
													.getFace()
											+ "--------------------"
											+ wxUserInfo.getData().getMemberInfo()
													.getNickName());*/	
						
							
					

							// send event
							LoginViewEvent event = new LoginViewEvent(
									LoginViewEvent.EVENT_UPDATE_WXLOGIN_MESSAGE);
							EventBus.getDefault().post(event);

						} else {

						}

					} catch (Exception e) {
						e.printStackTrace();
					}

				}

				@Override
				public void onFailure(int statusCode,
						cz.msebera.android.httpclient.Header[] headers,
						String responseString, Throwable throwable) {

				}

			});

		}	
	
	
}
